﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace Wsp365.AutomaticContentDatabaseSelector
{
    /// <summary>
    /// The SmallestContentDatabaseSiteCreationProvider selects the smallest
    /// of the available content databases and returns it to the SharePoint system.
    /// <see cref="http://www.fiechter.eu/blog/"/>
    /// </summary>
    public class SmallestContentDatabaseSiteCreationProvider: SPSiteCreationProvider
    {
        public override IEnumerable<SPContentDatabase> SelectContentDatabases(SPSiteCreationParameters creationParameters, IEnumerable<SPContentDatabase> contentDatabases)
        {
            try
            {
                SPDiagnosticsService.Local.WriteTrace(1,
                    new SPDiagnosticsCategory(Constants.DiagnosticCategoryName, TraceSeverity.Verbose, EventSeverity.Verbose),
                    TraceSeverity.Verbose,
                    "Start to select content database for new site collection",
                    null);

                List<SPContentDatabase> selectedContentDatabase = new List<SPContentDatabase>();
                //at least one content DB should be there
                if (contentDatabases.Count() > 0)
                {
                    // select the smallest one
                    SPContentDatabase smallestContentDb = contentDatabases
                        .Where(contentDb => contentDb.Status == SPObjectStatus.Online)
                        .OrderBy(contentDb => contentDb.DiskSizeRequired).First();

                    SPDiagnosticsService.Local.WriteTrace(2,
                        new SPDiagnosticsCategory(Constants.DiagnosticCategoryName, TraceSeverity.Verbose, EventSeverity.Verbose),
                        TraceSeverity.Verbose,
                        "Smallest content db identified: {0}",
                        smallestContentDb.Name);

                    selectedContentDatabase.Add(smallestContentDb);
                }
                return selectedContentDatabase;
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(3,
                    new SPDiagnosticsCategory(Constants.DiagnosticCategoryName, TraceSeverity.High, EventSeverity.ErrorCritical),
                    TraceSeverity.High,
                    "Automatic selection of smallest content db failed. Site collection is created with default content database. Exception: {0} \n StackTrace:{1}",
                    ex.Message,ex.StackTrace);
                return contentDatabases;
            }
        }
    }
}
